package com.nbufe.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nbufe.domain.dto.process.AddEmissionOriginDto;
import com.nbufe.domain.dto.process.AddProcessDto;
import com.nbufe.domain.dto.process.EditEmissionDto;
import com.nbufe.domain.dto.process.QueryEmissionOriginDetailVo;
import com.nbufe.domain.entity.EmissionOrigin;
import com.nbufe.domain.entity.Process;
import com.nbufe.domain.vo.process.ProcessEmissionOriginVo;
import com.nbufe.enums.AppHttpCodeEnum;
import com.nbufe.exception.SystemException;
import com.nbufe.mapper.EmissionOriginMapper;
import com.nbufe.mapper.ProcessMapper;
import com.nbufe.service.ProcessService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 工序表(Process)表服务实现类
 *
 * @author luzhiheng
 * @since 2023-12-26 15:11:29
 */
@Service("processService")
public class ProcessServiceImpl extends ServiceImpl<ProcessMapper, Process> implements ProcessService {

    @Resource
    private EmissionOriginMapper emissionOriginMapper;

    @Override
    public List<ProcessEmissionOriginVo> queryAllProcess() {
        List<Process> processList = this.list();
        if (CollectionUtils.isEmpty(processList)) {
            return new ArrayList<>();
        }
        Map<Long, List<EmissionOrigin>> emissionMap = emissionOriginMapper.selectList(null).stream().collect(Collectors.groupingBy(EmissionOrigin::getId));
        List<ProcessEmissionOriginVo> emissionOriginVoList = processList.stream().map(process -> {
            ProcessEmissionOriginVo vo = new ProcessEmissionOriginVo();
            vo.setProcessId(process.getId());
            vo.setProcessName(process.getName());
            List<Long> emissionIdList = JSON.parseArray(process.getEmissionOrigin(), Long.class);
            List<EmissionOrigin> emissionOriginList = new ArrayList<>();
            emissionIdList.forEach(e -> {
                List<EmissionOrigin> origins = emissionMap.get(e);
                if (!CollectionUtils.isEmpty(origins)) {
                    EmissionOrigin emissionOrigin = origins.get(0);
                    emissionOriginList.add(emissionOrigin);
                }
            });
            vo.setEmissionOriginList(emissionOriginList);
            return vo;
        }).collect(Collectors.toList());

        return emissionOriginVoList;
    }

    @Override
    public void deleteProcessById(Long id) {
        this.removeById(id);
    }

    @Override
    public void addProcess(AddProcessDto dto) {
        LambdaQueryWrapper<Process> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Process::getName, dto.getProcessName());
        List<Process> processList = this.list(queryWrapper);
        if (!CollectionUtils.isEmpty(processList)) {
            throw new SystemException(AppHttpCodeEnum.PROCESS_EXIST);
        }
        Process process = new Process();
        process.setName(dto.getProcessName());
        process.setEmissionOrigin("[]");
        this.save(process);
    }

    @Transactional
    @Override
    public void addEmissionOrigin(AddEmissionOriginDto dto) {
        queryEmissionOriginByNameAndIsExist(dto.getName());

        // 添加能源材料
        EmissionOrigin emissionOrigin = new EmissionOrigin(dto);
        emissionOriginMapper.insert(emissionOrigin);

        // 修改工序
        Process process = this.getById(dto.getProcessId());
        if (process == null) {
            throw new SystemException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        List<Long> ids = JSON.parseArray(process.getEmissionOrigin(), Long.class);
        ids.add(emissionOrigin.getId());
        process.setEmissionOrigin(JSON.toJSONString(ids));
        this.updateById(process);
    }

    @Override
    public QueryEmissionOriginDetailVo queryEmissionOriginDetail(Long id) {
        EmissionOrigin emissionOrigin = emissionOriginMapper.selectById(id);
        if (emissionOrigin == null) {
            throw new SystemException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        return new QueryEmissionOriginDetailVo(emissionOrigin);
    }

    @Override
    public void editEmissionOrigin(EditEmissionDto dto) {
        EmissionOrigin emissionOrigin = emissionOriginMapper.selectById(dto.getEmissionOriginId());
        if (emissionOrigin == null) {
            throw new SystemException(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        emissionOrigin.setProduceStage(JSON.toJSONString(dto.getStageList()));
        emissionOrigin.setName(dto.getName());
        emissionOriginMapper.updateById(emissionOrigin);
    }

    private void queryEmissionOriginByNameAndIsExist(String name) {
        LambdaQueryWrapper<EmissionOrigin> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EmissionOrigin::getName, name);
        List<EmissionOrigin> emissionOriginList = emissionOriginMapper.selectList(queryWrapper);
        if (!CollectionUtils.isEmpty(emissionOriginList)) {
            throw new SystemException(AppHttpCodeEnum.EMISSION_EXIST);
        }
    }

}
